package sms

import (
	"fmt"
    "htdemo.com/mycommon/public/tools"
	"math/rand"
	"net/http"
	"strconv"
	"strings"
	"time")

type RespDiDa struct {
	RespCode  string        `json:"respcode"`  //必选	请求状态码，取值00000（成功： 此步响应只表明客户的短信请求发送成功，不表明短信通道已经发送短信成功。） 具体可参照《附：返回状态码列表》
	RespDesc  string        `json:"respdesc"`  //可选	对返回状态码的描述 如：00000 代表成功
	FailCount string        `json:"failcount"` //必选	表示验证码通知短信发送失败的条数。
	FailList  []interface{} `json:"faillist"`  //可选	失败列表，包含失败号码、失败原因。
	SmsId     string        `json:"smsid"`     //必选	短信标识符。一个由32个字符组成的短信唯一标识符。
}

func SendSMSByDiDA(phone string) (respDiDa RespDiDa, err error) {
	vcode := generalVcode()
	//if isDev {   , expTime int, isDev bool
	//	vcode = 9999
	//	smsCache.Add(phone, time.Duration(expTime)*time.Minute, vcode)
	//	//smsCache.Add(phone, 10*time.Second, vcode)
	//	return
	//}
	//smsContent:="【婚恋交友】您的验证码为123456，请于2分钟内正确输入，如非本人操作，请忽略此短信。"
	accountSid := "2c9247da1ef1450094dfecffb56659e8"
	timestamp := time.Now().Format("20060102150405")
	authToken := "9758e0a78f9e4a92ad09ac57d265b8ac"
	params := "accountSid=2c9247da1ef1450094dfecffb56659e8&" +
		"param=%d,%d&templateid=747148740&to=%s&timestamp=%s&sig=%s"
	params = fmt.Sprintf(params, vcode, 2, phone, timestamp, tools.MD5(accountSid+authToken+timestamp))
	resp, err := http.Post("https://api.miaodiyun.com/20150822/industrySMS/sendSMS",
		"application/x-www-form-urlencoded",
		strings.NewReader(params))
	if err != nil {
		return
	}
	defer resp.Body.Close()
	err = tools.BindJson(resp.Body, &respDiDa)
	if err != nil {
		return
	}
	if respDiDa.RespCode != "00000" {
		err = fmt.Errorf("sms error")
	}
	smsCache.Add(phone, time.Duration(100)*time.Minute, vcode)
	//err = fmt.Errorf("%s phone`s %d of vcode", phone, vcode)
	return
}

func generalVcode() int {
	num := rand.Int()
	numStr := strconv.Itoa(num)
	if len(numStr) < 4 {
		numStr += strconv.Itoa(rand.Int())
	}
	vcode, _ := strconv.Atoi(numStr[:4])
	return vcode
}
